2

正则表达式的都是匹配和替换

PHP

搜索

preg_match*

/**
 * int preg_match* ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
 * $pattern  正则表达式
 * $subject  要匹配的字符串
 * &$matches 匹配到的字符串
 * return    匹配到的个数,没有匹配到返回0
 */

下面是例子

$pattern = "/\d{2}/";
$content = "12:34:56:78:9a";
// 执行一个正则表达式匹配, 非贪婪
if (preg_match ($pattern, $content, $m)){
    print_r($m);
}

// 执行一个全局正则表达式匹配, 贪婪
if ($c = preg_match_all($pattern, $content, $m)){
    echo "match numbers is ".$c."\n";
    print_r($m);
}

执行结果

$ php run.php
Array
(
    [0] => 12
)
match numbers is 4
Array
(
    [0] => Array
        (
            [0] => 12
            [1] => 34
            [2] => 56
            [3] => 78
        )
)

preg_grep

<?php
$pattern = "/^[a-z]*$/i";
$content = ["Mechanical Engineering",
            "Medicine",
            "Social Science",
            "Agriculture",
            "Commercial Science",
            "Politics" ];
// 匹配所有仅由有一个单词组成的科目名
$alonewords = preg_grep($pattern, $content);
foreach($alonewords as $key => $value){
    echo $key.$value."\n";
}
?>

输出结果

$ php run.php
1Medicine
3Agriculture
5Politics

替换

preg_replace

/**
 * mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
 * $pattern     正则表达式
 * $subject     要匹配的字符串
 * $replacement 用于替换的字符串或字符串数组, replacement和subject的类型相同
 * return       替换的后的对象,类型和subject相同
 */

例子

<?php
$content  = "Name: {Name}\nEmail: {Email}\nAddress: {Address}\n";
$patterns = ["/{Name}/", "/{Email}/", "/{Address}/"];
$replace  = ["Jaime", "xsu@viewtool.com", "Chongqing China"];
echo preg_replace($patterns, $replace, $content);
?>

输出结果

$php run.php
Name: Jaime
Email: xsu@viewtool.com
Address: Chongqing China

这个相当于就是最简单的模板实现了

php其他

PHP preg:http://php.net/manual/zh/ref.pcre.php
下面有所有的函数手册
preg_match
preg_match_all
preg_grep
preg_replace
preg_replace_callback
preg_replace_callback_array
preg_filter
grep_quote
grep_split
grep_last_error

PHP常用正则表达式汇总


javascript

如果是替换的正则表达式,可以自己写
如果仅仅是判断,推荐使用is.js这个库
官方网站
这里就不多介绍了, 官网上的非常的清楚


优de良
333 声望13 粉丝

好好写代码